package com.zmyuan.demo.netty.common;

import com.google.protobuf.ByteString;
import com.zmyuan.demo.netty.protobuf.MsgProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Handles a server-side channel.
 */
public class MsgServerHandler extends ChannelInboundHandlerAdapter { // (1)

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        MsgProtobuf.RequestMsg requestMsg = (MsgProtobuf.RequestMsg)msg;
        String cmd = requestMsg.getCmd();
        Object bean = Constants.MAPPING_INFO.get(cmd).getBean();
        Method method = Constants.MAPPING_INFO.get(cmd).getMethod();
        method.setAccessible(true);
        try {
            ByteString result = (ByteString)method.invoke(bean, requestMsg.getMsg());
            ctx.writeAndFlush(result);
            ctx.close();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
